<template>
  <div class="add-form">
    <div class="add-header">{{ title }}</div>
    <el-form
      :model="ruleForm"
      status-icon
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="员工头像:" prop="avatar">
        <el-upload
          class="avatar-uploader"
          action="https://jsonplaceholder.typicode.com/posts/"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="员工账号:" prop="username">
        <el-input v-model="ruleForm.username"></el-input>
      </el-form-item>
      <el-form-item label="员工姓名:" prop="name">
        <el-input v-model="ruleForm.name"></el-input>
      </el-form-item>
      <el-form-item label="公司地址:" prop="address">
        <el-input v-model="ruleForm.address"></el-input>
      </el-form-item>
      <el-form-item label="所属部门:" prop="department">
        <el-select v-model="ruleForm.department" placeholder="全部">
          <el-option label="销售部" value="销售部"></el-option>
          <el-option label="市场部" value="市场部"></el-option>
          <el-option label="总裁办" value="总裁办"></el-option>
          <el-option label="财务部" value="财务部"></el-option>
          <el-option label="IT部" value="IT部"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择职位:" prop="position">
        <el-select v-model="ruleForm.position" placeholder="全部">
          <el-option label="总经理" value="总经理"></el-option>
          <el-option label="部长" value="部长"></el-option>
          <el-option label="销售代表" value="销售代表"></el-option>
          <el-option label="销售组长" value="销售组长"></el-option>
          <el-option label="市场调研员" value="市场调研员"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="性别:" prop="sex">
        <el-select v-model="ruleForm.sex">
          <el-option label="男" value="男"></el-option>
          <el-option label="女" value="女"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="身份证号:" prop="idCard">
        <el-input v-model="ruleForm.idCard"></el-input>
      </el-form-item>
      <el-form-item label="手机号:" prop="phone">
        <el-input v-model="ruleForm.phone"></el-input>
      </el-form-item>
      <el-form-item label="QQ:" prop="qqNumber">
        <el-input v-model="ruleForm.qqNumber"></el-input>
      </el-form-item>
      <el-form-item label="家庭住址:" prop="homeAddress">
        <el-input v-model="ruleForm.homeAddress"></el-input>
      </el-form-item>
      <el-form-item label="出生日期:" prop="birthday">
        <el-date-picker
          type="date"
          placeholder="选择日期"
          v-model="ruleForm.birthday"
          value-format="yyyy/MM/dd HH:mm:ss"
          style="width: 100%"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="入职日期:" prop="hireDate">
        <el-date-picker
          type="date"
          placeholder="选择日期"
          v-model="ruleForm.hireDate"
          value-format="yyyy/MM/dd HH:mm:ss"
          style="width: 100%"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          type="password"
          v-model="ruleForm.password"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="resetpassword">
        <el-input
          type="password"
          v-model="ruleForm.resetpassword"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>



<script>
import { employeeAddApi, employeeEditApi } from "@/http/systemApi/employeeApi";
export default {
  data() {
    let validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.ruleForm.resetpassword !== "") {
          this.$refs.ruleForm.validateField("resetpassword");
        }
        callback();
      }
    };
    let validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.ruleForm.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    let shenfenzheng = (rule, value, callback) => {
      if (/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value)) {
        return callback();
      }
      callback(new Error("请输入正确的十五或十八位身份证"));
    };
    let shouji = (rule, value, callback) => {
      if (/^[1][3,4,5,7,8][0-9]{9}$/.test(value)) {
        return callback();
      }
      callback(new Error("请输入13,14,15,17,18开头的手机号"));
    };
    let username = (rule, value, callback) => {
      if (/^[\u2E80-\u9FFF]+$/.test(value)) {
        return callback();
      }
      callback(new Error("只能输入汉字"));
    };
    let qqnumber = (rule, value, callback) => {
      if (/^[0-9]{10}$/.test(value)) {
        return callback();
      }
      callback(new Error("只能输入数字"));
    };
    return {
      title: "添加员工",
      ruleForm: {
        id: "",
        avatar: "",
        idCard: "",
        username: "",
        address: "",
        sex: "",
        department: "",
        position: "",
        name: "",
        qqNumber: "",
        homeAddress: "",
        phone: "",
        birthday: "",
        hireDate: "",
        password: "",
        resetpassword: "",
      },
      imageUrl: "",
      rules: {
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { validator: validatePass, trigger: "blur" },
        ],
        resetpassword: [
          { required: true, message: "请再次输入密码", trigger: "blur" },
          { validator: validatePass2, trigger: "blur" },
        ],
        username: [
          { required: true, message: "请输入账号", trigger: "blur" },
          { min: 6, max: 12, message: "长度在6到12个字符", trigger: "blur" },
        ],
        name: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          { validator: username, trigger: "blur" },
        ],
        address: [
          { required: true, message: "请输入公司地址", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        phone: [
          { required: true, message: "请输入电话号码", trigger: "blur" },
          { validator: shouji, trigger: "blur" },
        ],
        qqNumber: [
          { required: true, message: "请输入QQ号", trigger: "blur" },
          {
            validator: qqnumber,
            message: "长度为9或者10个字符",
            trigger: "blur",
          },
        ],
        idCard: [
          { required: true, message: "请输入身份证号", trigger: "blur" },
          { validator: shenfenzheng, trigger: "blur" },
        ],
        department: [
          { required: true, message: "请选择部门", trigger: "blur" },
        ],
        position: [{ required: true, message: "请选择职位", trigger: "blur" }],
        sex: [{ required: true, message: "请选择性别", trigger: "blur" }],
      },
    };
  },
  activated() {
    if (this.$route.query.row) {
      this.ruleForm = this.$route.query.row;
      this.title="编辑员工";
    }
  },
  deactivated() {
    this.ruleForm = [];
    this.$refs["ruleForm"].resetFields();
    this.title="添加员工";
  },
  methods: {
    submit() {
      if (this.ruleForm.id) {
        this.editFrom(this.ruleForm);
      } else {
        this.submitForm(this.ruleForm);
      }
    },
    //编辑
    editFrom(ruleForm) {
      employeeEditApi(ruleForm)
        .then((res) => {
          console.log("编辑成功:", res);
          this.$router.push("/xitong-1/yuangong");
        })
        .catch((err) => {
          console.log("编辑失败:", err);
        });
    },

    //添加
    submitForm(ruleForm) {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          employeeAddApi(ruleForm)
            .then((res) => {
              console.log("添加成功:", res);
            })
            .catch((err) => {
              console.log("添加失败:", err);
            });
          this.$router.push("/xitong-1/yuangong");
          this.$refs["ruleForm"].resetFields();
        } else {
          console.log("error submit!!");
        }
      });
    },

    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },

    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
  },
};
</script>

<style lang="scss" scoped>
.add-header {
  height: 60px;
  line-height: 60px;
  padding: 0 20px;
  background-color: rgb(232, 232, 232);
}
.demo-ruleForm {
  width: 400px;
  margin: 25px auto 0;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  width: 100px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>